<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片布局区域 -->
    <el-card class="box-card">
      <!-- 添加分类按钮区域 -->
      <el-row>
        <el-col>
          <el-button @click="showAddCateDialog" plain type="primary">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 渲染分类区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
      >
        <!-- 是否有效区域 -->
        <template slot="isok" slot-scope="scope">
          <i
            style="color: lightgreen; fontSize: 16px"
            v-if="scope.row.cat_deleted === false"
            class="el-icon-success"
          ></i>
          <i style="color: red; fontSize: 16px" v-else class="el-icon-error"></i>
        </template>
        <!-- 排序区域 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="medium" v-if="scope.row.cat_level === 0" type="success">一级</el-tag>
          <el-tag size="medium" v-else-if="scope.row.cat_level === 1" type="warning">二级</el-tag>
          <el-tag size="medium" v-else type="danger">三级</el-tag>
        </template>
        <!-- 操作区域 -->
        <template slot="optin" slot-scope="scope">
          <el-button
            @click="showEditCateDialog(scope.row.cat_id)"
            plain
            size="mini"
            type="primary"
            icon="el-icon-edit"
          >编辑</el-button>
          <el-button
            @click="deleteCate(scope.row.cat_id)"
            plain
            size="mini"
            type="danger"
            icon="el-icon-delete"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- v-model 用来指级联选择器定选中以后的值，必须是数组 -->
          <!-- options 用来指级联选择器定数据源 -->
          <!-- props 用来指定级联选择器配置项 -->
          <!-- clearable 清空级联选择器 -->
          <!-- change 级联选择器重新选择时触发 -->
          <el-cascader
            v-model="selectKeys"
            :options="parentCateList"
            :props="catePorps"
            clearable
            @change="parentCateChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Category',
  data() {
    return {
      // 商品分类列表请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      cateList: [], // 商品分类列表数据
      total: 0, // 数据总条数
      // 配置表格树的竖列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'optin'
        }
      ],
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加商品分类数据对象
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加商品分类表单的验证规则
      addCateFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 级联选择器选中以后的值
      selectKeys: [],
      // 父级分类列表数据
      parentCateList: [],
      // 级联选择器配置项
      catePorps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },

      // 控制编辑分类对话框的显示与隐藏
      editCateDialogVisible: false,
      // 编辑商品分类数据对象
      editCateForm: {
        cat_id: null,
        cat_name: ''
      },
      // 编辑分类表单验证规则对象
      editCateFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 调用获取商品分类列表数据的方法
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('/categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
    },

    // pageSize 改变时会触发
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getCateList()
    },
    // 当页面改变时会触发
    handleCurrentChange(pageNum) {
      this.queryInfo.pagenum = pageNum
      this.getCateList()
    },

    // 展示添加分类对话框
    showAddCateDialog() {
      this.getParentList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类数据的列表
    async getParentList() {
      // 获取父级的数据
      const { data: res } = await this.$http.get('/categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.parentCateList = res.data
    },
    // 级联选择器重新选择时触发
    parentCateChange() {
      if (this.selectKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        this.addCateForm.cat_level = this.selectKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击确定，添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('/categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addCateDialogVisible = false
        this.getCateList()
      })
    },
    // 关闭添加分类对话框，重置表单
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()

      this.selectKeys = []

      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },

    // 展示编辑分类对话框
    async showEditCateDialog(catId) {
      const { data: res } = await this.$http.get(`/categories/${catId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editCateForm = res.data
      this.editCateDialogVisible = true
    },
    // 关闭编辑角色弹框，整个表单进行重置
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 点击确定，编辑分类
    editCate() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`/categories/${this.editCateForm.cat_id}`, {
          cat_name: this.editCateForm.cat_name
        })

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.editCateDialogVisible = false
      })
    },

    // 删除分类
    async deleteCate(catId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了删除')
      }

      const { data: res } = await this.$http.delete(`/categories/${catId}`)

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 20px;
}

.el-cascader {
  width: 100%;
}
</style>
